﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.IO;
using System.Text;

namespace CompanyCMS.App_Code
{
    public class LogHelper
    {
        private string logDirectory;
        private static object mux = new object();

        private LogHelper()
        {
            logDirectory = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["logDirectory"]); 
        }

        private static LogHelper _Instance;
        public static LogHelper Instance
        {
            get {
                if (_Instance == null)
                {
                    lock (mux)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new LogHelper();
                        }
                    }
                }
                return _Instance;
            }
        }

        public void WriteLog(string message)
        {
            string filepath = logDirectory + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            // 创建父目录
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }
            // 创建文件
            if (!File.Exists(filepath))
            {
                using (File.Create(filepath)) { }
            }

            using (StreamWriter sw = new StreamWriter(filepath, true, Encoding.UTF8))
            {
                sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"   " +message);
            }
        }
    }
}